package com.mos.simple.socket;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.mos.simple.result.ResultModel;
import jakarta.annotation.Resource;
import jakarta.websocket.Session;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.ByteBuffer;

/**
 * Description: <br/>
 * date: 2024/09/03 17:17<br/>
 *
 * @author 小尘哥<br />
 */
@Controller
@RequestMapping("websocket")
public class WebSocketController {

    @Resource
    private WebSocket webSocket;

    @RequestMapping("/send")
    @ResponseBody
    public ResultModel<String> send(@RequestParam(name = "msg") String msg,
                                    @RequestParam(name = "userId") String userId,
                                    @RequestParam(name = "receiveUserId") String receiveUserId,
                                    MsgEntity msgEntity) throws IOException {

        webSocket.onMsg(JSONUtil.toJsonStr(msgEntity));
        return ResultModel.defaultSuccess(msg);
    }

    @RequestMapping("/byteBuffer")
    @ResponseBody
    public ResultModel<String> sendByteBuffer( MultipartFile file,
                                    MsgEntity msgEntity) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.wrap(file.getBytes());
        Session session = WebSocket.livingSession.get(msgEntity.getReceiveUserId());
        webSocket.onMsg(byteBuffer,session);
        return ResultModel.defaultSuccess("");
    }

    @RequestMapping("/index")
    public String index() {
        return "socket/index";
    }

}
